//
//  JCClubMemberVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/22.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCClubMemberVC.h"
#import "JCClubInfoPlanWeekCell.h"
#import "JCClubMemberCell.h"
#import "JCClubInfoSectionHeader.h"
#import "JCClubApi.h"
#import "JCClubModel.h"
#import "JCClubMemberModel.h"
#import "JCClubSetupVC.h"
#import "YFAlertHelper.h"
#import "JCClubRankListMenuView.h"

#define kClubInfoCircleCellHeight   330
#define kClubInfoMemberCellHeight   69

@interface JCClubMemberVC ()<UITableViewDelegate, UITableViewDataSource, JCClubInfoPlanWeekCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) JCClubModel *clubModel;
@property (strong, nonatomic) NSArray <NSString *> *leftTitles;
@property (assign, nonatomic) NSInteger scorllIndex;
@property (assign, nonatomic) ClubMemberRankType rankType;
@property (assign, nonatomic) ClubMemberRankTimeType timeType;

@end

@implementation JCClubMemberVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    [self loadData];
}

- (void)loadData{
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getClubMemberDetailWithClubID:_clubID complete:^(NSError *error, JCClubModel *clubModel) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            [weakSelf.hud dismiss];
            weakSelf.clubModel = clubModel;
            [weakSelf.tableView reloadData];
        }
    }];
}

- (void)initCode{
    _rankType = ClubMemberRankTypeDuration;
    _timeType = ClubMemberRankTimeTypeThisWeek;
    [_tableView registerClass:[JCClubInfoSectionHeader class] forHeaderFooterViewReuseIdentifier:@"JCClubInfoSectionHeader"];
    self.navigationItem.title = @"Member";
    if (_watchClubType == WatchClubTypeMyMemberGeneral ||
        _watchClubType == WatchClubTypeMyMemberAdmin) {
        _leftTitles = @[@"Training Details Last Week",@"Plan For The Week",@"Schedule Of The Week"];
    }else{
        _leftTitles = @[@"Plan For The Week"];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return _clubModel?1:0;
    }else{
        return _clubModel.rankList.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        JCClubInfoPlanWeekCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([JCClubInfoPlanWeekCell class]) forIndexPath:indexPath];
        cell.watchType = _watchClubType;
        cell.isWatchMember = YES;
        cell.delegate = self;
        NSArray *sportItem;
        if (_watchClubType == WatchClubTypeMyMemberGeneral ||
            _watchClubType == WatchClubTypeMyMemberAdmin) {
            sportItem = @[_clubModel.lastWeekActiveTarget, _clubModel.clubWeekTarget, _clubModel.curWeekActiveTarget];
        }else{
            sportItem = @[ _clubModel.clubWeekTarget];
        }
        cell.sportItems = sportItem;
        return cell;
    }else{
        JCClubMemberCell *memberCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([JCClubMemberCell class]) forIndexPath:indexPath];
        [memberCell rankType:_rankType
                   rankModel:_clubModel.rankList[indexPath.row]
                   indexPath:indexPath];
        return memberCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return kClubInfoCircleCellHeight;
    }else{
        return kClubInfoMemberCellHeight;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kSectionHeaderHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    __weak typeof(self)weakSelf = self;
    JCClubInfoSectionHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([JCClubInfoSectionHeader class])];
    header.rightButtonAction = ^(SectionButtonType type){
        if (type == SectionButtonTypeSetup) {
            [weakSelf setupAction];
        }else if(type == SectionButtonTypeViewAll) {
        }else if(type == SectionButtonTypeRank) {
            [weakSelf menuAction];
        }
    };
    
    NSString *leftTitle;
    if (section == 0) {
        if (_leftTitles.count == 1) {
            leftTitle = @"Plan For The Week";
        }else{
            leftTitle = _leftTitles[_scorllIndex];
        }
    }else{
        leftTitle = @"Member Ranking";
    }
    [header setleftTitle:leftTitle];
    
    if (_watchClubType == WatchClubTypeMyMemberAdmin && section == 0) {
        [header setRightTitle:@"Set Up"];
        header.buttonType = SectionButtonTypeSetup;
    }else if (section == 1) {
        NSArray *titles = @[@"Exercise Duration",@"Batting Average",@"Shoot Speed"];
        [header setRightTitle:titles[_rankType - 1]];
        header.buttonType = SectionButtonTypeRank;
    }
//    else if ((_watchClubType == WatchClubTypeMyMemberGeneral ||
//               _watchClubType == WatchClubTypeMyMemberAdmin)
//              && section == 1) {
//        [header setRightTitle:@"Exercise duration"];
//        header.buttonType = SectionButtonTypeRank;
//    }
    
    return header;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == _tableView) {
        CGFloat sectionHeaderHeight;
        sectionHeaderHeight = 55;
        if (scrollView == _tableView) {
            if (scrollView.contentOffset.y<=sectionHeaderHeight && scrollView.contentOffset.y>=0) {
                scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
            } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
                scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
            }
        }
    }
}

- (void)scrollToIndex:(NSInteger)index{
    _scorllIndex = index;
    JCClubInfoSectionHeader *header = (JCClubInfoSectionHeader *)[_tableView headerViewForSection:0];
    [header setleftTitle:_leftTitles[index]];
}

- (void)menuAction{
    __weak typeof(self)weakSelf = self;
    JCClubRankListMenuView *alertView = [[UINib nibWithNibName:NSStringFromClass([JCClubRankListMenuView class]) bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil].firstObject;
    [alertView setupInitTimeType:_timeType rankType:_rankType];
    PopupViewController *popVC = [YFAlertHelper showPresentInView:nil alertView:alertView withAlertViewFrame:CGRectMake(0, 0, 281, 338) animationType:DetailViewControllerPresentAnimationTypeDown tapMaskViewDismiss:YES];
    __weak typeof(popVC)weakPopVC = popVC;
    alertView.dismissHandle = ^(ClubMemberRankTimeType timeType, ClubMemberRankType type) {
        [weakPopVC dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
        [weakSelf loadRankList:timeType rankType:type];
    };
}

- (void)loadRankList:(ClubMemberRankTimeType)timeType rankType:(ClubMemberRankType)rankType{
    __weak typeof(self)weakSelf = self;
    _rankType = rankType;
    _timeType = timeType;
    NSArray *titles = @[@"Exercise Duration",@"Batting Average",@"Shoot Speed"];
    JCClubInfoSectionHeader *header = (JCClubInfoSectionHeader *)[_tableView headerViewForSection:1];
    [header setRightTitle:titles[rankType - 1]];
    _rankType = rankType;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getClubMemberRankWithClubID:_clubID clubMemberRankTime:timeType clubMemberRankType:rankType complete:^(NSError *error, NSArray<JCClubMemberModel *> *rankList) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            [weakSelf.hud dismiss];
            [weakSelf.clubModel.rankList removeAllObjects];
            [weakSelf.clubModel.rankList addObjectsFromArray:rankList];
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }];
}

- (void)setupAction{
    __weak typeof(self)weakSelf = self;
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"ClubsExtension" bundle:[NSBundle mainBundle]];
    JCClubSetupVC *setupVC = [sb instantiateViewControllerWithIdentifier:NSStringFromClass([JCClubSetupVC class])];
    setupVC.clubID = _clubID;
    setupVC.defaultValueItem = _clubModel.clubWeekTarget;
    setupVC.dismissHandle = ^{
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:setupVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
